package com.lele.service;


import com.lele.domain.Role;
import com.lele.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class AdminUserDetailsService implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.getUserByUsername(username);
        // 不加密
        // user.setPassword("{bcrypt}" + user.getPassword());
        // 添加用户角色
        List<Role> roles = roleService.getRoleByUsername(username);


        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();

        for (Role role: roles) {
            String roleTag = role.getRoleDesc();

            grantedAuthorities.add(new SimpleGrantedAuthority(roleTag));
        }

        user.setAuthorities(grantedAuthorities);

        return user;
    }
}
